#!/usr/bin/env python

import serial
import sys
import time

#ser = serial.Serial("/dev/tty.PL2303-00001004", 57600, timeout=0)
ser = serial.Serial("/dev/tty.KeySerial1", 57600, timeout=0)

ser.open()

if not ser.isOpen():
	sys.exit()

if len(sys.argv) < 2:
	print "Usage:\n%s program.hex" % (sys.argv[0])
	sys.exit()

#print ser.inWaiting()

#while ser.inWaiting() > 0:
ser.readall(),

print "Bootloader! - loading ", sys.argv[1]

while True:
	str = ser.readall()
	if "-" in str:
		#print str
		break
	ser.write("##########"*1000)
	ser.flush()

time.sleep(0.25)

print "Got prompt"

ser.readall(),

ser.write("\nLD\n")
ser.flush()

time.sleep(1.0)

f = open(sys.argv[1])

ser.write(f.read())
ser.flush()

ser.readall(),

ser.write("\nGO\n")
ser.flush()

print "Done!"



#data = ""
#ser.setTimeout(5)
#while True:
#	last = ser.read(500)
#	print ".",
#	sys.stdout.flush()
#	data += last
#	if len(last) == 0 and len(data) > 0:
#		break;
#
#print "Read ", len(data), " bytes!"
